package com.noelchew.mylibrary;

import com.archermind.mylibrary.ResourceTable;
import com.noelchew.mylibrary.githublibrary.EmailListener;
import com.noelchew.mylibrary.githublibrary.SparkPostEmailUtil;
import com.noelchew.mylibrary.githublibrary.SparkPostRecipient;
import com.noelchew.mylibrary.githublibrary.SparkPostSender;
import com.noelchew.mylibrary.util.ProgressWheel;
import ohos.aafwk.ability.Ability;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.bundle.BundleInfo;
import ohos.multimodalinput.event.KeyEvent;
import ohos.rpc.RemoteException;


import static ohos.agp.components.Component.HORIZONTAL;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;


public class AppFeedback {

    private static CommonDialog myCommonDialog;
    private static CommonDialog sendCommonDialog;
    private static CommonDialog emailDialog;

    public static void feedback(final Context context, final String sparkPostApiKey, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, final AppFeedbackListener listener, final CommonDialog commonDialog) {
        feedback(context, sparkPostApiKey, senderEmailAddress, senderName, recipientEmailAddress, "", ResourceTable.String_nc_utils_feedback, listener, commonDialog, false);
    }

    public static void feedback(final Context context, final String sparkPostApiKey, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, final AppFeedbackListener listener, final CommonDialog commonDialog, boolean enableNormalEmailAsBackup) {
        feedback(context, sparkPostApiKey, senderEmailAddress, senderName, recipientEmailAddress, "", ResourceTable.String_nc_utils_feedback, listener, commonDialog, enableNormalEmailAsBackup);
    }

    public static void feedback(final Context context, final String sparkPostApiKey, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, int selectionDialogTitleResourceId, final AppFeedbackListener listener, final CommonDialog commonDialog, boolean enableNormalEmailAsBackup) {
        feedback(context, sparkPostApiKey, senderEmailAddress, senderName, recipientEmailAddress, "", selectionDialogTitleResourceId, listener, commonDialog, enableNormalEmailAsBackup);
    }

    // this is used when user has submitted a bad rating
    public static void feedbackWithBadRating(final Context context, final String sparkPostApiKey, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, final int rating, final AppFeedbackListener listener, final CommonDialog commonDialog) {
        feedback(context, sparkPostApiKey, senderEmailAddress, senderName, recipientEmailAddress, "Rated " + rating + "/5", ResourceTable.String_nc_utils_feedback_for_bad_rating, listener, commonDialog, false);
    }

    // this is used when user has submitted a bad rating
    public static void feedbackWithBadRating(final Context context, final String sparkPostApiKey, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, final int rating, final AppFeedbackListener listener, final CommonDialog commonDialog, boolean enableNormalEmailAsBackup) {
        feedback(context, sparkPostApiKey, senderEmailAddress, senderName, recipientEmailAddress, "Rated " + rating + "/5", ResourceTable.String_nc_utils_feedback_for_bad_rating, listener, commonDialog, enableNormalEmailAsBackup);
    }

    public static void feedback(final Context context, final String sparkPostApiKey, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, final String additionalDetails, int selectionDialogTitleResourceId, final AppFeedbackListener listener, final CommonDialog commonDialog, boolean enableNormalEmailAsBackup) {
        String appName = "AppFeedback App";
        try {
            BundleInfo bundleInfo = context.getBundleManager().getBundleInfo(context.getBundleName(), 0);
            appName = context.getString(ResourceTable.String_nc_utils_feedback) + "-" + bundleInfo.name + ":" + bundleInfo.originalName;
        } catch (RemoteException e) {
            listener.onError(e);
        }
        final String subject = appName;
        feedback(context, sparkPostApiKey, subject, senderEmailAddress, senderName, recipientEmailAddress, additionalDetails, selectionDialogTitleResourceId, listener, commonDialog, enableNormalEmailAsBackup);
    }

    public static void feedback(final Context context, final String sparkPostApiKey, final String subject, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, final String additionalDetails, int selectionDialogTitleResourceId, final AppFeedbackListener listener, final CommonDialog commonDialog, final boolean enableNormalEmailAsBackup) {
        if (!checkContext(context, listener)) {
            return;
        }

        myCommonDialog = new CommonDialog(context);
        DirectionalLayout dialogLayout = (DirectionalLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_sendselect, null, false);
        dialogLayout.findComponentById(ResourceTable.Id_text_feedbackAnonymously).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                sendFeedbackAnonymously(context, sparkPostApiKey, subject, senderEmailAddress, senderName, recipientEmailAddress, additionalDetails, listener, commonDialog, enableNormalEmailAsBackup);
            }
        });
        dialogLayout.findComponentById(ResourceTable.Id_text_feedbackByEmail).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                sendFeedbackByEmail(context, subject, recipientEmailAddress, listener);
            }
        });
        myCommonDialog.setContentCustomComponent(dialogLayout)
                .setAlignment(LayoutAlignment.CENTER)
                .setSize(950, 550)
                .show();

    }

    public static void sendFeedbackAnonymously(final Context context, final String sparkPostApiKey, final String subject, final String senderEmailAddress, final String senderName, final String recipientEmailAddress, final String additionalDetails, final AppFeedbackListener listener, final CommonDialog commonDialog, final boolean enableNormalEmailAsBackup) {
        if (!checkContext(context, listener)) {
            return;
        }

        DirectionalLayout myLayout1 = new DirectionalLayout(context);
        ProgressWheel pwTwo = new ProgressWheel(context);
        DirectionalLayout.LayoutConfig config1 = new DirectionalLayout.LayoutConfig(MATCH_PARENT, MATCH_CONTENT);
        DirectionalLayout.LayoutConfig config2 = new DirectionalLayout.LayoutConfig(200, 200);

        myLayout1.setOrientation(HORIZONTAL);
        myLayout1.setAlignment(LayoutAlignment.CENTER);
        myLayout1.setLayoutConfig(config1);
        pwTwo.setLayoutConfig(config2);
        pwTwo.setDelayMillis(5);
        pwTwo.startSpinning();

        Text text = new Text(context);
        text.setText(" please wait...");
        text.setTextSize(16, Text.TextSizeType.FP);
        text.setLayoutConfig(new DirectionalLayout.LayoutConfig(MATCH_PARENT, MATCH_PARENT));
        text.setMarginLeft(25);

        myLayout1.addComponent(pwTwo);
        myLayout1.addComponent(text);

        CommonDialog progressDialog = new CommonDialog(context);

        progressDialog.setContentCustomComponent(myLayout1)
                .setTitleText("  Loading")
                .setAlignment(LayoutAlignment.CENTER)
                .setSize(700, 350);

        DirectionalLayout dialogLayout1 = (DirectionalLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_content, null, false);
        TextField textFieldType = (TextField) dialogLayout1.findComponentById(ResourceTable.Id_dialog_text_field_type);

        myCommonDialog.remove();

        sendCommonDialog = new CommonDialog(context);
        sendCommonDialog
                .setContentCustomComponent(dialogLayout1)
                .setSize(950, MATCH_CONTENT);

        sendCommonDialog.siteKeyboardCallback(new IDialog.KeyboardCallback() {
            @Override
            public boolean clickKey(IDialog iDialog, KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() == KeyEvent.KEY_BACK) {
                    return true;
                }
                return false;
            }
        });

        Button btnCancel = (Button) dialogLayout1.findComponentById(ResourceTable.Id_btn_cancel);
        Button btnOkOne = (Button) dialogLayout1.findComponentById(ResourceTable.Id_btn_ok_one);

        btnCancel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                sendCommonDialog.remove();
            }
        });

        btnOkOne.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                sendCommonDialog.remove();

                String userFeedBackType = textFieldType.getText().trim();
                if (userFeedBackType == null || userFeedBackType.length() <= 0) {
                    new ToastDialog(context)
                            .setText(context.getString(ResourceTable.String_nc_utils_feedback_invalid_feedback_type))
                            .setSize(700, MATCH_CONTENT)
                            .setAlignment(LayoutAlignment.BOTTOM)
                            .show();
                    return;
                }
                if (!checkContext(context, listener)) {
                    return;
                }
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.remove();
                }
                DirectionalLayout dialogLayout2 = (DirectionalLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_content1, null, false);
                emailDialog = new CommonDialog(context);
                emailDialog.setContentCustomComponent(dialogLayout2)
                        .setSize(950, MATCH_CONTENT);


                emailDialog.siteKeyboardCallback(new IDialog.KeyboardCallback() {
                    @Override
                    public boolean clickKey(IDialog iDialog, KeyEvent keyEvent) {
                        if (keyEvent.getKeyCode() == KeyEvent.KEY_BACK) {
                            return true;
                        }
                        return false;
                    }
                });

                dialogLayout2.findComponentById(ResourceTable.Id_btn_cancel_two).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        emailDialog.remove();
                    }
                });

                dialogLayout2.findComponentById(ResourceTable.Id_btn_ok_two).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        TextField textFieldEmail = (TextField) dialogLayout2.findComponentById(ResourceTable.Id_dialog_text_field_email);
                        String userEmail = textFieldEmail.getText().trim();
                        final boolean isSenderEmailValid = isValidEmail(userEmail);

//                  TODO 邮箱格式验证
//                        if (!isSenderEmailValid) {
//                            new ToastDialog(context).setText(context.getString(ResourceTable.String_nc_utils_feedback_invalid_feedback_email))
//                                    .setSize(700, MATCH_CONTENT)
//                                    .setAlignment(LayoutAlignment.BOTTOM)
//                                    .show();
//                            return;
//                        }

                        EmailListener emailListener = new EmailListener() {
                            @Override
                            public void onSuccess() {

                                if (!checkContext(context, listener)) {
                                    return;
                                }

                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.remove();
                                }
                                new CommonDialog(context)
                                        .setTitleText(context.getString(ResourceTable.String_nc_utils_feedback))
                                        .setContentText(context.getString(ResourceTable.String_nc_utils_feedback_send_success))
                                        .setAlignment(LayoutAlignment.CENTER)
                                        .setSize(950, 550)
                                        .show();

                                if (isSenderEmailValid) {

                                    if (listener != null) {
                                        listener.onFeedbackNonAnonymouslySuccess(userEmail);
                                    }
                                } else {

                                    if (listener != null) {
                                        listener.onFeedbackAnonymouslySuccess();
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                if (!checkContext(context, listener)) {
                                    return;
                                }
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.remove();
                                }
                                if (listener != null) {
                                    listener.onFeedbackAnonymouslyError(e);
                                }
                                if (enableNormalEmailAsBackup) {
                                    sendFeedbackByEmail(context, subject, userFeedBackType, recipientEmailAddress, null);
                                }
                            }
                        };
                        try {
                            SparkPostEmailUtil.sendEmail(context,
                                    sparkPostApiKey,
                                    subject,
                                    userFeedBackType +
                                            "\n\nUser Email: " + userEmail.trim() +
                                            "\n\n" + additionalDetails.trim(),
                                    new SparkPostSender(senderEmailAddress, senderName),
                                    new SparkPostRecipient(recipientEmailAddress),
                                    emailListener);
                        } catch (Exception e) {
                            e.printStackTrace();
                            new ToastDialog(context).setText(context.getString(ResourceTable.String_nc_utils_error)).setAlignment(LayoutAlignment.BOTTOM).show();
                        }

                        progressDialog.show();
                        emailDialog.remove();
                        sendCommonDialog.remove();

                    }
                });
                emailDialog.show();


            }
        });

        sendCommonDialog.show();

    }

    public static void sendFeedbackByEmail(Context context, String subject, String recipientEmailAddress, AppFeedbackListener listener) {
        if (!checkContext(context, listener)) {
            return;
        }
        //TODO EmailUtil intent没有有效action
        EmailUtil.sendEmailByIntent(context, subject, context.getString(ResourceTable.String_nc_utils_feedback_email_message), recipientEmailAddress);
        if (listener != null) {
            listener.onFeedbackViaPhoneEmailClient();
        }
    }


    public static void sendFeedbackByEmail(Context context, String subject, String message, String recipientEmailAddress, AppFeedbackListener listener) {
        if (!checkContext(context, listener)) {
            return;
        }
        EmailUtil.sendEmailByIntent(context, subject, message, recipientEmailAddress);
        if (listener != null) {
            listener.onFeedbackViaPhoneEmailClient();
        }
    }

    private static boolean isValidEmail(String emailStr) {
        String format = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        return emailStr.matches(format);
    }

    //TODO     获取context强调色
    private static int fetchAccentColor(Context context) {
//        TypedValue typedValue = new TypedValue();
//        TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorAccent});
//        int color = a.getColor(0, 0);
//        a.recycle();

        int intColor = Color.getIntColor("#FFB6C1");
        return intColor;
    }

    private static boolean checkContext(Context context, AppFeedbackListener listener) {
        if (context == null) {
            if (listener != null) {
                listener.onFeedbackAnonymouslyError(new Throwable("NULL context."));
            }
            return false;
        } else if (context instanceof Ability && isActivityFinishingOrDestroyed((Ability) context)) {
            if (listener != null) {
                listener.onFeedbackAnonymouslyError(new Throwable("Activity is not alive."));
            }
            return false;
        }
        return true;
    }

    private static boolean isActivityFinishingOrDestroyed(Ability ability) {
//      ohos 暂时无需判断sdk版本
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            return ability.isTerminating() ;
//        } else {
        return ability.isTerminating();
//        }
    }
}